<template>
    <Form ref="form" :model="form" :rules="ruleValidate" label-position="left" :label-width="100">
        <FormItem label="教学周" prop="jxweek_id">
            <Select v-model="form.jxweek_id" :multiple="!this.condition" placeholder="请选择教学周">
                <Option v-for="(item,index) in weekData" :value="item.id" :key="index">{{ item.name?item.name:item.mn_name }}</Option>
            </Select>
        </FormItem>
        <Table border stripe :columns="columns" :data="dataList" :loading="tableload"></Table>

        <div style="text-align:center;margin-top:10px">
            <Button  type="primary" @click="handleAdd" icon="plus-round">增加</Button>
        </div> 

        <FormItem>
            <Button type="primary" :loading="btnload" @click="handleSubmit('form')">{{ condition?'修改':'添加' }}</Button>
        </FormItem>
    </Form>
</template>

<script>
export default {
    props: {
        condition: {
            type: [Boolean, Number],
            default: false
        }
    },
    data () {
        return {
            weekList:[
                {
                    value:1,
                    lable:'星期一'
                },
                {
                    value:2,
                    lable:'星期二'
                },
                {
                    value:3,
                    lable:'星期三'
                },
                {
                    value:4,
                    lable:'星期四'
                },
                {
                    value:5,
                    lable:'星期五'
                },
                {
                    value:6,
                    lable:'星期六'
                },
                {
                    value:7,
                    lable:'星期日'
                },
            ],
            weekData:[],
            dataList:[],
            departmentList:[],
            positionList:[],
            userList:[],
            columns:[
                {
                    title: '星期',
                    minWidth: 150,
                    render: (h, params) => {
                        let ss=[]
                        this.weekList.forEach((item)=>{
                            ss.push(h('Option', {
                                props: {
                                    value:item.value,
                                }
                            },item.lable))
                        })
                        return h('Select',{
                            style: {
                                // width: '100px',
                            },
                            props:{
                                value:this.dataList[params.index].type//默认选中第一个（v-model）
                            },
                            on:{
                                'on-change':(value) => {
                                    this.dataList[params.index].type=value
                                },
                            }
                        },ss);
                    }
                },
                {
                    title: '部门',
                    minWidth: 150,
                    render: (h, params) => {
                        let ss=[]
                        this.departmentList.forEach((item)=>{
                            ss.push(h('Option', {
                                props: {
                                    value:item.id,
                                }
                            },item.department_name))
                        })
                        return h('Select',{
                            style: {
                                // width: '100px',
                            },
                            props:{
                                value:this.dataList[params.index].department_id//默认选中第一个（v-model）
                            },
                            on:{
                                'on-change':(value) => {
                                    this.tableload=true
                                    this.dataList[params.index].department_id=value
                                    this.dataList[params.index].userList=[]
                                    this.$http.get(`${this.url2}[${value}]`).then(val=>{
                                        this.dataList[params.index].positionList = val.data.map(el => {
                                            let obj ={
                                                id: el.id,
                                                position_name: el.position_name.zh?el.position_name.zh:el.position_name.mn
                                            }
                                            return obj
                                        })
                                        this.tableload=false
                                    }).catch(err => {
                                        this.tableload=false
                                    })
                                    
                                },
                            }
                        },ss);
                    }
                },
                {
                    title: '岗位',
                    minWidth: 150,
                    render: (h, params) => {
                        let ss=[]
                        params.row.positionList.forEach((item)=>{
                            ss.push(h('Option', {
                                props: {
                                    value:item.id,
                                }
                            },item.position_name))
                        })
                        return h('Select',{
                            style: {
                                // width: '100px',
                            },
                            props:{
                                value:this.dataList[params.index].position_id//默认选中第一个（v-model）
                            },
                            on:{
                                'on-change':(value) => {
                                    this.tableload=true
                                    this.dataList[params.index].position_id=value
                                    this.$http.get(`${this.url3}[${value}]`).then(val=>{
                                        this.dataList[params.index].userList = val.data
                                        this.tableload=false
                                    }).catch(err => {
                                        this.tableload=false
                                    })
                                                            
                                },
                            }
                        },ss);
                    }
                },
                {
                    title: '人员',
                    minWidth: 150,
                    render: (h, params) => {
                        let ss=[]
                        params.row.userList.forEach((item)=>{
                            ss.push(h('Option', {
                                props: {
                                    value:item.id,
                                }
                            },item.teacher.teacher_name.zh))
                        })
                        return h('Select',{
                            style: {
                                // width: '100px',
                            },
                            props:{
                                value:this.dataList[params.index].lader_id//默认选中第一个（v-model）
                            },
                            on:{
                                'on-change':(value) => {
                                    this.dataList[params.index].lader_id=value
                                    
                                },
                            }
                        },ss);
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 150,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px',
                                },
                                on: {
                                    click: () => {
                                        this.confirm(params.row,params.index)
                                    }
                                }
                            }, '删除'),
                        ]);
                    }
                },
            ],
            tableload: false,
            btnload: false,
            form:{
                jxweek_id: [],
            },
            selUrl: 'api/watchlist/v1/weekcheck/find/' + this.condition,

            url1: 'api/user/v1/get/all/department/list',
            url2: 'api/user/v1/get/position/list?department_id=',
            url3: 'api/user/v1/get/position/users?position_id=',
            url4: 'api/course/v1/course_arrange/cycle',
            ruleValidate: {
                jxweek_id: [
                    { required: true, type: this.condition?'number':'array' , message: '请选择教学周', trigger: 'change' }
                ],
            },
        }
    },
    methods: {
        
        /************************************************************
         * 
         * 表单验证
         * @param   {name}            要验证的表单
         * 
         ************************************************************/
        handleSubmit (name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.btnload = true
                    // if(this.condition){
                    //     this.saveUrl=`api/watchlist/v1/weekcheck/edit/${this.condition}`
                    //     this.saveType=this.$http.put
                    // }else{

                    //     this.saveUrl='api/watchlist/v1/weekcheck/add'
                    //     this.saveType=this.$http.post
                    // }
                    this.Submit()
                } else {
                    this.$Message.error('请检查填写内容');
                }
            })
        },
        
        /************************************************************
         * 
         * 执行添加数据
         * 
         ************************************************************/
        Submit () {
            let datas = JSON.parse(JSON.stringify(this.dataList))
            let ss = false
            let weekarr =[]
            let formlist={
                    jxweek_id:this.condition ? [this.form.jxweek_id] : this.form.jxweek_id,
                    week:[]
                }
            if(!datas.length){
                this.$Message.error('至少添加1条数据');
                this.btnload = false
                return
            }
            datas.forEach((item)=>{
                if(!item.department_id || !item.lader_id || !item.position_id || !item.type){
                    ss = true
                }
                weekarr.push(item.type)
                formlist.week.push({
                    department_id:item.department_id,
                    lader_id:item.lader_id,
                    position_id:item.position_id,
                    type:item.type,
                    
                })
            })
            if(ss){
                this.$Message.error('请检查填写内容');
                this.btnload = false
                return
            }
            if(new Set(weekarr).size !== weekarr.length){
                this.$Message.error('星期不得重复');
                this.btnload = false
                return
            }
            this.$http.post('api/watchlist/v1/weekcheck/add', formlist).then(val=>{
                this.btnload = false
                this.$emit('requery',true)
            }).catch(err => {
                this.btnload = false 
            })
        },
        
        /************************************************************
         * 
         * 执行修改数据
         * 
         ************************************************************/
        editSubmit () {
            let datas = JSON.parse(JSON.stringify(this.form))
            datas.department_id = datas.datas[0]
            datas.position_id = datas.datas[1]

            delete datas.datas
            this.$http.post(this.editurl, datas).then(val=>{
                this.btnload = false
                this.$emit('requery',true)
            }).catch(err => {
                this.btnload = false 
            })
        },
        
        /************************************************************
         * 
         * （部门）
         * 
         ************************************************************/
        departmentData () {
            this.tableload=true
            this.$http.get(this.url1).then(val=>{
                this.departmentList = val.data.map(el => {
                    let obj ={
                        id: el.id,
                        department_name: el.department_name.zh?el.department_name.zh:el.department_name.mn,
                    }
                    return obj
                })
                this.tableload=false
            }).catch(err => {
                this.tableload=false
            })
        },
        
        /************************************************************
         * 
         * 获取当前教学周
         * 
         ************************************************************/
        weekfun () {
            this.$http.get(this.url4).then(val=>{
                this.weekData = val.data
            }).catch(err => {

            })
        },
        
        /************************************************************
         * 
         * 获取岗位
         * 
         ************************************************************/
        positionfun (value,item) {
            this.tableload=true
            this.$http.get(`${this.url2}[${value}]`).then(val=>{
                
                // item.positionList = val.data
                item.positionList = val.data.map(el => {
                    let obj ={
                        id: el.id,
                        position_name: el.position_name.zh?el.position_name.zh:el.position_name.mn,
                    }
                    return obj
                })
                this.tableload=false
            }).catch(err => {
                this.tableload=false
            })
        },
        
        /************************************************************
         * 
         * 获取人员
         * 
         ************************************************************/
        userfun (value,item) {
            this.tableload=true
            this.$http.get(`${this.url3}[${value}]`).then(val=>{
                item.userList = val.data
                this.tableload=false
            }).catch(err => {
                this.tableload=false
            })
        },

        
        /************************************************************
         * 
         * 排序
         * 
         * 
         ************************************************************/
        compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;
            }
        },

        
        /************************************************************
         * 
         * 单条数据查询（修改）
         * 
         ************************************************************/
        selData () {
            this.$http.get(this.selUrl).then(val=>{
                let dd = val.data.sort(this.compare('type'))
                this.form.jxweek_id=[val.data[0].jxweek_id]
                this.dataList = dd.map(item=>{
                    let ss = {
                        id:item.id,
                        department_id:item.department_id,
                        position_id:item.position_id,
                        lader_id:item.lader_id,
                        type:item.type,
                        positionList:[],
                        userList:[],
                    }
                    this.positionfun(item.department_id,ss)
                    this.userfun(item.position_id,ss)
                    return ss 
                })
            }).catch(err => {
            })
        },
        /************************************************************
         * 
         * 增加
         * 
         ************************************************************/
        handleAdd () {
            if(this.dataList.length>=7){
                this.$Message.error('最多添加7条数据');
                return
            }
            this.dataList.push({department_id:null,id:null,position_id:null,lader_id:null,type:null,positionList:[],userList:[]})
        },

        /************************************************************
         * 
         * 执行删除操作
         * 
         ************************************************************/
        confirm (row,index) {
            this.$Modal.confirm({
                title: '数据删除',
                content: '<p>您确定要删除这些数据吗?</p>',
                onOk: () => {
                    if(row.id){
                        this.tableload=true
                        this.$http.delete(`api/watchlist/v1/weekcheck/dels/[${row.id}]`)
                        .then(val=>{  
                            this.dataList.splice(index, 1);  
                            this.$Message.success(val.message);  
                            this.tableload=false         
                        })
                        .catch(err=>{
                            console.log(err);
                            if(err.code && err.code==422) {
                                this.$Message.error(err.message);
                            }
                            this.tableload=false   
                        })
                    }else{
                        this.dataList.splice(index, 1);
                    }
                },
            });
        },
    },
    created () {
        if (this.condition) this.selData ()
        this.departmentData ()
        this.weekfun()
    },
}
</script>